package domein;

import gui.*;
import java.io.*;
import java.net.*;
import java.util.logging.Level;
import java.util.logging.Logger;

public class Service implements Runnable {
    private Socket connSocket;
    private Thread thread;
    private boolean run = true;
    private Request req;
    private Servlet svlt = new Servlet();
    private MyTextPane textPane;
	private String contentBase;

    public Service(Socket newSocket) {
        System.out.println("Service Socket: " + newSocket);
        connSocket = newSocket;
        textPane = new MyTextPane();
    }

    public boolean closeSocket() {
        return true;
    }

    public void start() {
        if (thread == null) {
            thread = new Thread(this);
        }
        thread.start();
    }

    public void run() {
        try {
            SocketInputStream sis = new SocketInputStream(connSocket.getInputStream());
            textPane.append("Connection start: "+ connSocket.getRemoteSocketAddress()+"\n");
            textPane.append("---------------------------------\n\n");
            while (run) {
                try {
                    req = new Request(sis,this.contentBase);
                    textPane.append(req.toString());
                    if (req.getMETHOD().equals("GET")) {
                       Response resp = svlt.service(req);
                       connSocket.getOutputStream().write(resp.getBYTES());
                    } else {
                        ///
                    }
                    sis.close();
                } catch (Exception ex) {
                    run = false;
                }
            }
            connSocket.close();
        } catch (IOException ex) {
            try {
                connSocket.close();
            } catch (IOException ex1) {
                /// error
            }
        }

    }

    public void stopRun() {
        run = false;
    }
    public MyTextPane getTextPane(){
        return textPane;
    }

	public void setContentBase(String contentBase) {
		this.contentBase = contentBase;
		
	}
}
